from google.appengine.ext import db

from Location import *
from util import *

class Trip(db.Model):
    userId = db.IntegerProperty()
    duration = db.FloatProperty() # in hours
    userDuration = db.FloatProperty() # in hours
    #startLocation = db.ReferenceProperty(Location, collection_name="tripStartLocation_set")
    #endLocation = db.ReferenceProperty(Location, collection_name="tripEndLocation_set")
    startLocationId = db.StringProperty(Location)
    endLocationId = db.StringProperty(Location)

    def save(self):
        self.put()
        self.id = self.key().id()

def Trip_getOrCreate(userId, start, end):
    #print "Get trip: ", userId, start.string(), end.string()
    #print "Get trip: ", userId, start.key(), end.key()
    #tripQ = db.GqlQuery("SELECT * FROM Trip WHERE userId=:1 AND startLocationId=:2 AND endLocationId=:3", userId, start, end)
    tripQ = db.GqlQuery("SELECT * FROM Trip WHERE userId=:1 AND startLocationId=:2 AND endLocationId=:3", userId, start.string(), end.string())
    trip = tripQ.get()
    if not trip:
        #print "CREATED NEW TRIP"
        directions = Directions(start, end)
        travelTime = float(TravelTime(directions).seconds) / 3600.0
        trip = Trip()
        trip.userId = userId
        #trip.startLocation = start
        #trip.endLocation = end
        trip.startLocationId = start.string()
        trip.endLocationId = end.string()
        trip.duration = travelTime
        trip.userDuration = travelTime
        trip.save()
    return trip

            
